import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from '@/views/login'
// // 首页
// import Layout from '@/views/layout'
// //
// import Home from '@/views/home'
// // 视频
// import Video from '@/views/video'
// // 问答
// import Question from '@/views/question'
// // 我的
// import User from '@/views/user'
// import Chat from '@/views/user/chat'
// // 搜索
// import Search from '@/views/search'
// // 导入路由对象， 补充beforeEach
import store from '@/store/index.js'
// // 搜索结果页
// import Result from '@/views/search/result'
// import Article from '@/views/article/index.vue'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/index.vue')
  },
  // 首页
  {
    path: '/',
    name: 'layout',
    component: () => import('../views/layout/index.vue'),
    children: [
      // 默认显示的子路由
      { path: '', component: () => import('../views/home/index.vue') },
      { path: '/video', component: () => import('../views/video/index.vue') },
      { path: '/question', component: () => import('../views/question/index.vue') },
      { path: '/user', component: () => import('../views/user/index.vue') }
    ]
  },
  {
    path: '/search',
    name: 'Search',
    component: () => import('../views/search/index.vue')// Search
  },
  {
    path: '/search/result',
    name: 'Searchresult',
    component: () => import('../views/search/result.vue')// SearchResult
  },
  {
    path: '/article/:id',
    name: 'Article',
    component: () => import('@/views/article/index.vue')
  },
  {
    path: '/user/profile',
    name: 'userProfile',
    component: () => import('@/views/user/profile.vue')
  },
  {
    path: '/user/chat',
    name: 'chat',
    component: () => import('@/views/user/chat.vue')
  }

]

const router = new VueRouter({
  routes
})
// 路由守卫
// 当路由变化时，这个函数就会执行
// localhost:8080/#/a   ---->  localhost:8080/#/b
router.beforeEach(function (to, from, next) {
  console.log('路由变化了', to, from, next)
  // to:   去到哪里？ /b
  // from: 从哪里来？ /a
  // next: 是一个函数，用来自定义路由的跳转
  //  (1) next() 表示放行，让路由从from进入到to
  //  (2) next(其它路由),表示不去to，而进入指定的路由
  // next()

  // 如果你要去的页面是需要登陆才能访问的，则先去检查一下你是否登陆：
  //  - 没有登陆，转到登陆页
  //  - 正常放行

  // fullPath: 包含了path及查询字符串的内容
  if (to.poth === '/user') {
    // 检查是否登录
    if (store.state.tokenInfo.token) {
      console.log('你没有登录，不可以访问')
      next()
    } else {
      console.log('没有身份证，转到login')
      next('/login?backto=' + to.fullPath)
    }
  } else {
    // 如果登陆了，就不能回到login
    // if (to.path === '/login') {
    //   if (this.$store.state.tokenInfo.token) {
    //     this.$router.push('/') // next('/')
    //   } else {
    //     next()
    //   }
    // } else {
    //   next()
    // }
    next()
  }
})

export default router
